package com.ruiyi.subway.web;

import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class WorkingModeFilter implements Filter {

    private Map<String, String> resourcePrefixes = new HashMap<String, String>();
    private List<String> workingModes = new ArrayList<String>();
    private String env;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        resourcePrefixes.put("sa", "SAAS");
        resourcePrefixes.put("hq", "HQ");
        resourcePrefixes.put("br", "BRANCH");
        resourcePrefixes.put("cm", "*");

        Properties properties = new Properties();
        try {
            properties.load(this.getClass().getClassLoader().getResourceAsStream("yc-vcs.properties"));
            String modes = properties.getProperty("vcs.modes.working");
            for (String mode : modes.split(",")) {
                if (mode == null || mode.isEmpty()) {
                    continue;
                }
                workingModes.add(mode.trim());
            }
            env = properties.getProperty("vcs.env", "prod");
        } catch (IOException e) {
            throw new ServletException("load yc-vcs.properties from classpath failed.", e);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String protocol = request.getProtocol().toUpperCase();
        if (protocol.startsWith("HTTP")) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            if (!resourceRequestAllowed(httpRequest)) {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.setStatus(HttpStatus.FORBIDDEN.value());
                return;
            }
        }
        chain.doFilter(request, response);

    }

    private boolean resourceRequestAllowed(HttpServletRequest httpRequest) {
        //开发测试环境不做拦截
        if (!"prod".equals(this.env)) {
            return true;
        }
        String requestURI = httpRequest.getRequestURI();
        String[] reses = requestURI.split("/");
        if (reses.length <= 2) {
            return true;
        }
        String modePrefix = reses[2];
        String mode = resourcePrefixes.get(modePrefix);
        if ("*".equals(mode)) {
            return true;
        }
        if (workingModes.contains(mode)) {
            return true;
        }
        return false;
    }

    @Override
    public void destroy() {

    }

}
